package fr.alesia.capital.match;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import fr.alesia.capital.bean.Pays;
import fr.alesia.capital.dao.PaysDao;
import fr.alesia.capital.factory.DaoFactory;

public class PaysFinderUnimatch implements PaysFinder{

	private PaysDao dao = DaoFactory.getPaysDao();
	private Unimatch matcher = UnimatchSimple.getInstance();
	private static PaysFinder instance = null;
	
	private PaysFinderUnimatch(){
		
		dao = DaoFactory.getPaysDao();
		matcher = UnimatchSimple.getInstance();
	}
	
	public static PaysFinder getInstance(){
		if(instance == null){
			instance = new PaysFinderUnimatch();
		}
		return instance;
	}
	
	public Pays find(String terms) {

		List<Pays> pays = dao.getAll();
		SortedMap<Integer, Pays> matches = new TreeMap<Integer, Pays>();
		Pays result = null;
		
		for (Pays item : pays) {
			
			int note = matcher.unimatch(
				terms,
				item.getPays()
			);
			if(note > Unimatch.MATCH){
				
				matches.put(note, item);
			}
			else{
				
				String[] capitales = item.getCapitale().split("/");
				for (String capitale : capitales) {
					note = matcher.unimatch(
							terms,
							capitale.trim()
						);
						if(note > Unimatch.MATCH){
							
							matches.put(note, item);
						}
				}
				capitales = null;
			}
		}
		
		if(matches.size() > 0){
			result = matches.get(matches.lastKey());
		}
		pays = null;
		
		return result;
	}

	public Pays findByCapitale(String capitale) {
		
		List<Pays> pays = dao.getAll();
		SortedMap<Integer, Pays> matches = new TreeMap<Integer, Pays>();
		Pays result = null;
		
		for (Pays item : pays) {
			
			int	note = matcher.unimatch(
				capitale,
				item.getCapitale()
			);
			if(note > Unimatch.MATCH){		
				matches.put(note, item);
			}
		}
		
		if(matches.size() > 0){
			result = matches.get(matches.lastKey());
		}
		pays = null;
		
		return result;
	}

	@Override
	public Pays findByPays(String pays) {
		
		List<Pays> items = dao.getAll();
		SortedMap<Integer, Pays> matches = new TreeMap<Integer, Pays>();
		Pays result = null;
		
		for (Pays item : items) {
			
			int	note = matcher.unimatch(
				pays,
				item.getPays()
			);
			if(note > Unimatch.MATCH){		
				matches.put(note, item);
			}
		}
		
		if(matches.size() > 0){
			result = matches.get(matches.lastKey());
		}
		pays = null;
		
		return result;
	}

	
}
